package com.michale.admin.controller.tool;

import com.github.pagehelper.PageInfo;
import com.michale.common.annotation.Log;
import com.michale.common.character.ClassConvert;
import com.michale.common.enmus.BusinessType;
import com.michale.common.result.AjaxResult;
import com.michale.common.result.PageResult;
import com.michale.generator.domain.GenTable;
import com.michale.generator.domain.GenTableColumn;
import com.michale.generator.service.GenTableColumnService;
import com.michale.generator.service.GenTableService;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Michale
 * @apiNote 生成代码
 */
@Api(tags = "生成代码管理")
@RestController
@RequestMapping("tool/generator")
public class GeneratorController extends BaseController {
    @Resource
    private GenTableService genTableService;
    @Resource
    private GenTableColumnService genTableColumnService;

    /**
     * 查询生成表数据
     *
     * @param genTable 查询参数
     * @return 生成表数据列表
     */
    @GetMapping("/tableList")
    @PreAuthorize("@security.isPermission('tool:generator:list')")
    public PageResult getTableList(GenTable genTable) {
        startPage();
        List<GenTable> genTableEntityList = genTableService.selectTableList(genTable);
        PageInfo<GenTable> pageInfo = new PageInfo<>(genTableEntityList);
        return pageResult(pageInfo);
    }

    /**
     * 查询数据库列表
     *
     * @param genTable 查询参数
     * @return 数据库列表
     */
    @GetMapping("/dbTableList")
    @PreAuthorize("@security.isPermission('tool:generator:list')")
    public PageResult dbTableList(GenTable genTable) {
        startPage();
        List<GenTable> genTableList = genTableService.selectDbTableList(genTable);
        PageInfo<GenTable> pageInfo = new PageInfo<>(genTableList);
        return pageResult(pageInfo);
    }

    /**
     * 导入表结构（保存）
     *
     * @param tables 表信息
     */
    @PostMapping("/importTable")
    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PreAuthorize("@security.isPermission('tool:generator:list')")
    public AjaxResult importTableSave(String tables) {
        String[] tableNames = ClassConvert.toStringArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return success();
    }

    /**
     * 查询详情
     */
    @GetMapping(value = "/{tableId}")
    @PreAuthorize("@security.isPermission('tool:generator:query')")
    public AjaxResult getTableInfo(@PathVariable Long tableId) {
        GenTable genTableInfo = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tables", tables);
        map.put("list", list);
        map.put("info", genTableInfo);
        return success(map);
    }

    /**
     * 修改代码生成业务
     *
     * @param genTable 表信息
     */
    @PutMapping("/updateTable")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PreAuthorize("@security.isPermission('tool:generator:edit')")
    public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return success();
    }

    /**
     * 删除代码生成
     *
     * @param tableIds 表编号
     */
    @DeleteMapping("/deleteTable/{tableIds}")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @PreAuthorize("@security.isPermission('tool:generator:remove')")
    public AjaxResult deleteGenTable(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return success();
    }

    /**
     * 预览代码
     * @param tableId 表编号
     * @return 预览代码
     */
    @GetMapping("/preview/{tableId}")
    @PreAuthorize("@security.isPermission('tool:generator:preview')")
    public AjaxResult preview(@PathVariable("tableId") Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return success(dataMap);
    }
    /**
     * 批量生成代码
     *
     * @param response 请求信息
     * @param tables   表信息
     */
    @GetMapping("/batchGenCode")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @PreAuthorize("@security.isPermission('tool:generator:code')")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = ClassConvert.toStringArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"michale.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名
     * @return 代码信息
     */
    @GetMapping("/genCode/{tableName}")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @PreAuthorize("@security.isPermission('tool:generator:code')")
    public AjaxResult genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return success();
    }

    /**
     * 同步数据库
     * @param tableName 表名
     */
    @GetMapping("/syncDatabase/{tableName}")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PreAuthorize("@security.isPermission('tool:generator:edit')")
    public AjaxResult syncDatabase(@PathVariable("tableName") String tableName) {
        genTableService.syncDatabase(tableName);
        return success();
    }
}
